package ari.com.netty.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.example.echo.EchoServerHandler;

/**
 * Echoes back any received data from a client.
 * 
 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
 * 
 * @version $Rev: 2080 $, $Date: 2010-01-26 18:04:19 +0900 (Tue, 26 Jan 2010) $
 * 
 */
public class NettyEchoServer {
	private static ServerBootstrap bootstrap;
	static {
		bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool()));
	}

	public static void start(final int portNumber) throws Exception {
		// Set up the pipeline factory.
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new EchoServerHandler());
			}
		});
		System.out.println("Binding to port " + portNumber);
		// Bind and start to accept incoming connections.
		bootstrap.bind(new InetSocketAddress(portNumber));
		System.out.println("[AFTER] Binding to port " + portNumber);
	}

	public static void stop() throws Exception {
		System.out.println("Releasing all resources");
		bootstrap.getFactory().releaseExternalResources();
		System.out.println("Releasing all resources [DONE]");
	}
}
